﻿using OpenApi.OAuths.Datas.DbModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenApi.OAuths
{
	public class AccessTokenDbService
	{
		public static AccessTokenDbService Instance = new AccessTokenDbService();

		private OAuth2Entities DbSession()
		{
			return new OAuth2Entities();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="consumerKey"></param>
		/// <param name="userId"></param>
		/// <returns></returns>
		public AccessToken Create(string consumerKey, string userId)
		{
			AccessToken accessToken = new AccessToken()
			{
				ConsumerKey = consumerKey,
				UserId = userId,
				Token = Guid.NewGuid().ToString("N"),
				Secret = Guid.NewGuid().ToString("N"),
				Status = 0,
				AddTime = DateTime.Now
			};

			using (var db = this.DbSession())
			{
				db.AccessTokenSet.Add(accessToken);
				db.SaveChanges();
			}

			return accessToken;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="consumerKey"></param>
		/// <param name="userId"></param>
		/// <returns></returns>
		public AccessToken Get(string consumerKey, string userId)
		{
			using (var db = this.DbSession())
			{
				return db.AccessTokenSet.Where(at => at.UserId == userId && at.ConsumerKey == consumerKey).SingleOrDefault();
			}
		}

		/// <summary>
		/// 根据用户标识获取或者创建Token对象
		/// </summary>
		/// <param name="consumerKey">消费者</param>
		/// <param name="userId">用户标识</param>
		/// <returns></returns>
		public AccessToken GetOrCreate(string consumerKey, string userId)
		{
			AccessToken accessToken = this.Get(consumerKey, userId);
			if (accessToken == null)
			{
				accessToken = this.Create(consumerKey, userId);
			}
			return accessToken;
		}

		/// <summary>
		/// 获取AccessToken信息
		/// </summary>
		/// <param name="token">获取AccessToken信息</param>
		/// <returns></returns>
		public AccessToken GetAccessToken(string token)
		{
			using (var db = this.DbSession())
			{
				return db.AccessTokenSet.Where(at => at.Token == token).SingleOrDefault();
			}
		}

		/// <summary>
		/// 是否存在指定的Token
		/// </summary>
		/// <param name="token">指定的Token信息</param>
		/// <returns>True：存在，False：不存在</returns>
		public bool ExistsAccessToken(string token)
		{
			using (var db = this.DbSession())
			{
				return db.AccessTokenSet.Where(at => at.Token == token).Count() > 0;
			}
		}
	}
}